<?php
/**
 * Description of PresentacionP
 *
 * @author Nelifer
 */
include_once('BDManager.class.php');
require('Inventario.class.php');

class OrdenCompra {
    var $con;
    function OrdenCompra(){
        $this->con=new BDManager();
    }

    function insertar($campos){
        if($this->con->conectar()==true){
            $sql1 = "INSERT INTO ordenescompras (pro_id, odc_codigo, odc_fechacreacion, odc_horacreacion, usu_id) VALUES('".$campos[0]."', '".$campos[1]."', 
                            '".$campos[2]."', '".$campos[3]."', '".$campos[4]."')";
            $res1 = mysql_query($sql1);	

            $BD = new BDManager();
            $odcId = $BD->get_current_insert_id("ordenescompras");

            $ioc = $campos[5];
            $sql2 = "";

            for ($i = 0, $count = count($ioc); $i < $count; $i++) {
                if ($ioc[$i][4]==1||$ioc[$i][4]==2){
                    $sql2 = $sql2 .  "('".$ioc[$i][1]."', '".$odcId."', '".$ioc[$i][2]."'), ";
                }
                
            }
            $sql2 =  "INSERT INTO itemsordenescompras (map_id, odc_id, ioc_cant) VALUES " . $sql2;
            $sql2 = substr($sql2, 0, (strlen($sql2)-2) )  . ";";
            //echo "Sql2: $sql2";
            $res2 = mysql_query($sql2);	
            return ($res1 && $res2) ? true : false;
			
        }
    }

    function actualizar($campos, $id){
        if($this->con->conectar()==true){
						
            $ioc = $campos[1];
	    //print_r($ioc );
            $sqlInsert = "";
            $sqlUpdate = "";			
            $sqlDelIds = "";			
            $sqlDelete = "";
			
            for ($i = 0, $count = count($ioc); $i < $count; $i++) {
				
                if ($ioc[$i][4]==1 && $ioc[$i][5]==0){ //Insertar
                    $sqlInsert = $sqlInsert .  "('".$ioc[$i][1]."', '".$campos[0]."', '".$ioc[$i][2]."'), ";
                }else if($ioc[$i][4]==2){ //Modificar
                    $sqlUpdate = "UPDATE itemsordenescompras SET map_id = '".$ioc[$i][1]."', ioc_cant = '".$ioc[$i][2]."' WHERE ioc_id = '".$ioc[$i][5]."';" ;
		    //echo "SQlUpdate : $sqlUpdate"; 
                    mysql_query($sqlUpdate);
                }else if ($ioc[$i][4]==3){ //Elimianr
                    $sqlDelIds = $sqlDelIds . $ioc[$i][5]. ",";
                }
            }
            if (strlen($sqlInsert) > 0 ){
                $sqlInsert = "INSERT INTO itemsordenescompras (map_id, odc_id, ioc_cant) VALUES " . $sqlInsert;
				$sqlInsert = substr($sqlInsert, 0, (strlen($sqlInsert)-2) )  . ";";                    
                $res1 = mysql_query($sqlInsert);	
            }
            if (strlen($sqlUpdate) > 0){
                //$res1 = 	
            }
            if (strlen($sqlDelIds) > 0){
                $sqlDelIds = substr($sqlDelIds, 0, (strlen($sqlDelIds)-1) )  ;      
				            
                $sqlDelete = "DELETE FROM itemsordenescompras WHERE ioc_id IN (". $sqlDelIds." ) "; 
				echo $sqlDelete;   
                $res1 = mysql_query($sqlDelete);
            }
          
            return true;
        }		
    }
    public function actualizarCantItemsOdc($campos = null){
        $res1 = 0;
        if($this->con->conectar()==true){
            for ($i = 0, $count = count($campos[0]); $i < $count; $i++) { 
                $cant = ((strlen($campos[1][$i]) > 0) ? $campos[1][$i] : 0); 

                $cantTotal = $campos[2][$i]+ $cant; 

                $sqlUpdate = "UPDATE itemsordenescompras SET ioc_cantrecibida = '".$cantTotal."' WHERE ioc_id = '".$campos[0][$i]."'" ;                      
                mysql_query($sqlUpdate);
                
                $obj = new Inventario();
                $invId = $obj->insertarInventario(1, $campos[3][$i], $cant);
                if($invId != -1){
                    $res1 = $obj->insertarRegistroInv($invId, $cant, $campos[5], $campos[6], $campos[4]);
                }
            } 
        }
        return ($res1==1) ? true : false;

    }
    public function getConsulta($id){
        if($this->con->conectar()==true){
        $sql = "SELECT pro.pro_id, pro.pro_razonsocial, odc.odc_id, odc.odc_codigo, pro.pro_razonsocial, pro.pro_cirif, ".
                "pro.pro_direccion, pro.pro_tlfoficina ".
                "FROM ordenescompras odc ".
                "INNER JOIN proveedores pro on pro.pro_id = odc.pro_id ".
                "WHERE odc_id=$id";
            return mysql_query($sql);
        }
    }
    public function getConsultaOrdenFactura($id){
        if($this->con->conectar()==true){
        $sql = "SELECT cli.cli_id, cli.cli_razonsocial, fve.fve_id, fve.fve_nro, cli.cli_rif, ".
                "cli.cli_direccion, cli.cli_tlfoficina ".
                "FROM facturasventas fve ".
                "INNER JOIN clientes cli on cli.cli_id = fve.cli_id ".
                "WHERE fve.fve_id=$id";
            return mysql_query($sql);
        }
    }
    function getConsultas(){
        if($this->con->conectar()==true){
            return mysql_query("SELECT pre_id, pre_nombre, pre_unidad FROM presentacionesproductos ORDER BY pre_id DESC");
        }
    }

    function eliminar($id){
        if($this->con->conectar()==true){
                return mysql_query("DELETE FROM ordenescompras WHERE odc_id=".$id);
        }
    }
    private function countRec($fname,$tname,$where) {
        $con = null;
        $sql = "SELECT count($fname) FROM $tname $where";
        if($this->con->conectar()==true){
            $con = $this->con->conectar();
            $result = mysql_query($sql);
        }
        while ($row = mysql_fetch_array($result)) {
            return $row[0];
        }
    }
    
    public function consultar_grid($page=null, $rp=null, $sortname=null, $sortorder=null, $query=null, $letter_pressed=null, $qtype=null, $tipoProducto=null){
        if (!$sortname) $sortname = 'name';
        if (!$sortorder) $sortorder = 'desc';
        if($query!=''){
             $where = "WHERE `".$qtype."` LIKE '%".$query."%' ";
        } else {
            $where ='';
        }
        if($letter_pressed!=''){
            $where = "WHERE `".$qtype."` LIKE '".$letter_pressed."%' ";	
        }
        if($letter_pressed=='#'){
            $where = "WHERE `".$qtype."` REGEXP '[[:digit:]]' ";
        }
        $sort = "ORDER BY $sortname $sortorder";

        if (!$page) $page = 1;
        if (!$rp) $rp = 10;
        $start = (($page-1) * $rp);
        $limit = "LIMIT $start, $rp";
        if($tipoProducto==1){
            $sql = "SELECT odc.odc_id, odc.odc_codigo, pro.pro_razonsocial, odc.odc_fechacreacion, ".
                          "CONCAT(usu.usu_nombre, ' '  ,usu.usu_apellido) usu_nombre  ".
                    "FROM ordenescompras odc ".
                          "INNER JOIN proveedores pro on pro.pro_id = odc.pro_id ".
                          "INNER JOIN usuarios usu on usu.usu_id = odc.usu_id $where $sort $limit";
            $total = $this->countRec('odc_id','ordenescompras',$where);
            
        }else if($tipoProducto==2){
            $sql = "SELECT fve.fve_id, fve.fve_nro, cli.cli_razonsocial, fve.fve_fechacreacion, ".
                          "CONCAT(usu.usu_nombre, ' '  ,usu.usu_apellido) usu_nombre  ".
                    "FROM facturasventas fve ".
                          "INNER JOIN clientes cli on cli.cli_id = fve.cli_id ".
                          "INNER JOIN usuarios usu on usu.usu_id = fve.usu_id $where $sort $limit";
            $total = $this->countRec('fve_id','facturasventas',$where);
        }


        $con = $this->con->conectar();
        $result = mysql_query($sql);
        //$this->con->close($con); OJO CERRAR CONEXIONES

        // Return JSON data
        $data = array();
        $data['page'] = $page;
        $data['total'] = $total;
        $data['rows'] = array();
        if($tipoProducto == 1){
            while ($row = mysql_fetch_assoc($result)) {
                $fecha = substr($row['odc_fechacreacion'], 6,7) . '/'. substr($row['odc_fechacreacion'], 4,-2) . '/'. substr($row['odc_fechacreacion'], 0,4);
                $data['rows'][] = array(
                'id' => $row['odc_id'],
                'cell' => array($row['odc_id'], $row['odc_codigo'], $row['pro_razonsocial'], $fecha,
                                $row['usu_nombre'])
                );
            }            
        }else if($tipoProducto==2){
            while ($row = mysql_fetch_assoc($result)) {
                $fecha = substr($row['fve_fechacreacion'], 6,7) . '/'. substr($row['fve_fechacreacion'], 4,-2) . '/'. substr($row['fve_fechacreacion'], 0,4);
                if($row['fve_nro']=="0") $nro = "-";
                else $nro = $row['fve_nro'];
                $data['rows'][] = array(
                'id' => $row['fve_id'],
                'cell' => array($row['fve_id'], $nro, $row['cli_razonsocial'], $fecha,
                                $row['usu_nombre'])
                );
            }

        }

        echo json_encode($data);
    }
    public function getConsultaJson( $odcId = null ){
        $result = $this->getConsulta($odcId);

        $row_array   = array();
        while ($row = mysql_fetch_assoc($result)) {
            $row_array['id']     = $row['pro_id'];
            $row_array['cirif']  = $row['pro_cirif'];
            $row_array['razonS'] = $row['pro_razonsocial'];
            $row_array['direcF'] = $row['pro_direccion'];
            $row_array['tlfOfi'] = $row['pro_tlfoficina'];
            $row_array['odcCod'] = $row['odc_codigo'];
        }
        return $row_array;
        
    }
    public function getOdc($proId = null, $odcId = null){
        $data   = array();
        if($proId != null){
            $obj    = new Proveedor();
            $aOdc   = $obj->getArrayProveedor($proId);
        }else{
            $aOdc   = $this->getConsultaJson($odcId);
        }
        if($this->con->conectar()==true){
            $sql = "SELECT ioc.ioc_id, ioc.ioc_cant, ioc.ioc_cantrecibida, map.map_id, map.map_codigo, map.map_nombre ".
                    "FROM itemsordenescompras ioc  ".
                        "INNER JOIN ordenescompras odc on odc.odc_id = ioc.odc_id ".
                        "INNER JOIN materiasprimas map on map.map_id = ioc.map_id ".
                    "WHERE odc.odc_id=$odcId";
            $result =  mysql_query($sql);
            while ($row = mysql_fetch_assoc($result)) {
                $row_array['ioc_id']            = $row['ioc_id'];
                $row_array['ioc_cant']          = $row['ioc_cant'];
                $row_array['ioc_cantrecibida']  = $row['ioc_cantrecibida'];
                $row_array['map_id']            = $row['map_id'];
                $row_array['map_codigo']        = $row['map_codigo'];
                $row_array['map_nombre']        = $row['map_nombre'];
                array_push($data,$row_array);
            }
        }
        $a = array();
        array_push($a, $aOdc);
        array_push($a, $data);
        //print_r($a);
        echo json_encode($a);
    }



}

?>
